<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import '@/assets/less/TableExpand.less'
import { postAction } from '@api/manage'
import QcPlanReportModal from './modules/QcPlanReportModal.vue'
import store from '@/store'
import { getAction } from '@api/manage'

export default {
  name: 'FinishedProductInspectionReport',
  components: { QcPlanReportModal },
  mixins: [JeecgListMixin],
  data() {
    return {
      description: '检验单表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '检验单号',
          align: 'center',
          dataIndex: 'reportNumber'
        },
        {
          title: '计划单号',
          align: 'center',
          dataIndex: 'planNumber'
        },
        {
          title: '生产车间',
          align: 'center',
          dataIndex: 'productionShop_dictText'
        },
        {
          title: '执行日期',
          align: 'center',
          dataIndex: 'executionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '抽检数量',
          align: 'center',
          dataIndex: 'samplingQuantity'
        },
        {
          title: '检验结果',
          align: 'center',
          dataIndex: 'inspectionResult_dictText'
        },
        {
          title: '检验员',
          align: 'center',
          dataIndex: 'createBy_dictText'
        },
        {
          title: '检验部门',
          align: 'center',
          dataIndex: 'sysOrgCode_dictText'
        },
        {
          title: '检验日期',
          align: 'center',
          dataIndex: 'inspectionDate',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/qms/inspection/plan/report/finished-product/list',
        delete: '/qms/inspection/plan/report/delete',
        deleteBatch: '/qms/inspection/plan/report/deleteBatch',
        exportXlsUrl: '/qms/inspection/plan/report/finished-product/exportXls',
        revoke: '/qms/inspection/plan/report/revoke'
      },
      settingColumns: [],
      dictOptions: {}
    }
  },
  created() {
  },
  beforeDestroy() {
    // 组件销毁前保存列设置到sessionStorage
    sessionStorage.setItem('finishedProductInspectionReportColumns', JSON.stringify(this.settingColumns))
  },
  mounted() {
    // 组件挂载后恢复列设置
    const savedColumns = JSON.parse(sessionStorage.getItem('finishedProductInspectionReportColumns'))
    if (savedColumns && savedColumns.length > 0) {
      this.settingColumns = savedColumns
    }
  },
  computed: {
    // 添加计算属性，根据settingColumns过滤显示的列
    computedColumns() {
      // 获取所有列的数据索引
      const allColumns = this.columns.map(col => col.dataIndex)
      // 如果设置了自定义列，则过滤显示
      if (this.settingColumns && this.settingColumns.length > 0) {
        return this.columns.filter(col => 
          this.settingColumns.includes(col.dataIndex) || 
          !col.dataIndex || // 保留没有dataIndex的列（如序号列）
          col.dataIndex === 'action' // 保留操作列
        )
      }
      // 默认显示所有列
      return this.columns
    }
  },
  methods: {
    onColSettingsChange(checkedValues) {
      // 存储到localStorage
      sessionStorage.setItem('finishedProductInspectionReportColumns', JSON.stringify(checkedValues))
      localStorage.setItem('finishedProductInspectionReportColumns', JSON.stringify(checkedValues))
      this.settingColumns = checkedValues
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      const params = this.getQueryParams()
      this.loading = true
      params.status = '1'
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
          this.loading = false
        })
    },
    initDictConfig() {
    },
    handleCancel(record) {
      postAction(this.url.revoke, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.loadData()
          } else {
            this.$message.warning(res.message)
          }
        })
    },
    handleDetail(record) {
      this.$refs.modalForm.detail(record)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.reportType = 'finished-product'
    },
    printPreview(record) {
      const token = store.getters.token
      const id = record.id
      window.open(`${window._CONFIG['domianURL']}/jmreport/view/1101746599990517760?token=${token}&id=${id}`, '_blank')
    },
  }
}
</script>

<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
      <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
      >项
      <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      <span style="float:right;">
        <a-popover title="自定义列" trigger="click" placement="leftBottom">
          <template slot="content">
            <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
              <a-row style="width: 400px">
                <template v-for="(item,index) in defColumns">
                  <template v-if="item.key!=='rowIndex'&& item.dataIndex!=='action'">
                      <a-col :span="12"><a-checkbox :value="item.dataIndex"><j-ellipsis :value="item.title" :length="10"></j-ellipsis></a-checkbox></a-col>
                  </template>
                </template>
              </a-row>
            </a-checkbox-group>
          </template>
          <a><a-icon type="setting" />设置</a >
        </a-popover>
      </span>
    </div>
    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        class="j-table-force-nowrap1"
        :scroll="{x:true}"
        :columns="computedColumns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <a-divider type="vertical" />
          <a-popconfirm
            title="确定撤销吗?"
            @confirm="() => handleCancel(record)">
           <a>撤销</a>
          </a-popconfirm>
          <a-divider type="vertical" />
          <a @click="printPreview(record)">单据打印</a>
        </span>
      </a-table>
    </div>
    <qc-plan-report-modal ref="modalForm" @ok="modalFormOk" />
  </a-card>
</template>

<style scoped>
@import '~@assets/less/common.less';
</style>